// Copyright (c) 2020 Presto Labs Pte. Ltd.
// Author: linchuan

#pragma once

#include <cstdio>
#include <map>
#include <memory>
#include <string>
#include <vector>

#include <rapidjson/document.h>

#include "coin2/exchange/base/order/order.h"
#include "coin2/exchange/ftx_common/api_order/native_private_client.h"
#include "coin2/exchange/ftx/symbology/currency.h"
#include "coin2/exchange/ftx/symbology/product.h"

namespace coin2::exchange::ftx::order_v1 {

class FtxParser : public base::order::BaseParser {
 public:
  using FtxOrderSubTopicId = FtxNativePrivateClient::FtxOrderSubTopicId;

 public:
  const ParseResult& ParseRawMessage(const RawMessage& msg) override;
  AccountBalance ParseBalance(const JsonValue& doc) override;
  bool ParseRawBalance(const JsonValue& doc, RawBalanceMap* raw_balance_map);

  const coin::proto::OrderEvent& ParseSubmitResponseEvent(
      const base::order::IOrderContext* order_context,
      const std::shared_ptr<AsioHttpContext>& http_context);
  const coin::proto::OrderEvent& ParseCancelResponseEvent(
      const base::order::IOrderContext* order_context,
      const std::shared_ptr<AsioHttpContext>& http_context);

  const coin::proto::OrderEvent& ParseRestOrderInfoListEvent(const JsonValue& data);
  const coin::proto::OrderEvent& ParseWsOrderInfoListEvent(const JsonValue& data);
  const coin::proto::OrderEvent& ParseRestFillInfoListEvent(const JsonValue& data);
  const coin::proto::OrderEvent& ParseWsFillInfoListEvent(const JsonValue& data);

 private:
  void ParseSubmitResponse();
  void ParseCancelResponse();
  void ParseRestOrdersInfo();
  void ParseRestFillInfoList();
  void ParseRestAccountBalance();
  void ParseRestDeposit();
  void ParseRestWithdrawal();
  void ParseWsMessage();

  ProductOrderBundle ParseWsOrderInfoListV2(const JsonValue& data);
  ProductFillBundle ParseWsFillInfoListV2(const JsonValue& data);
  coin::proto::ProductFillElement ParseFillInfo(const JsonValue& data);
  coin::proto::ProductOrderElement ParseOrderInfo(const JsonValue& data);

 private:
  coin::proto::OrderEvent order_event_;
  bool is_account_balance_initialized_ = false;
  std::map<std::string, std::string> transfer_deposit_map_;
  bool is_transfer_deposit_initialized_ = false;
  std::map<std::string, std::string> transfer_withdrawal_map_;
  bool is_transfer_withdrawal_initialized_ = false;
};

}  // namespace coin2::exchange::ftx::order_v1
